package com.itheima.algorithm.binarytree;

import java.util.LinkedList;

/**
 * @author: TylerZhong
 * @description: 根据后缀表达式构造表达式树
 */
public class E08ExpressionTree {
    public TreeNode2 constructExpressionTree(String[] tokens) {
        LinkedList<TreeNode2> stack = new LinkedList<>();
        for (String token : tokens) {
            switch (token) {
                case "+","-","*","/" -> {
                    TreeNode2 right = stack.pop();
                    TreeNode2 left = stack.pop();
                    TreeNode2 parent = new TreeNode2(token);
                    parent.left = left;
                    parent.right = right;
                    stack.push(parent);
                }
                default -> stack.push(new TreeNode2(token));
            }
        }
        return stack.peek();
    }
}
